{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d13185ff-01fe-48e7-814e-4c1acaf0686a",
   "metadata": {},
   "outputs": [],
   "source": [
    "import tensorflow as tf\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "cifar10 = tf.keras.datasets.cifar10\n",
    "(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n",
    "x_train, x_test = tf.cast(x_train, dtype=tf.float32)/255.0, tf.cast(x_test, dtype=tf.float32)/255.0\n",
    "y_train, y_test = tf.cast(y_train, dtype=tf.int32), tf.cast(y_test, dtype=tf.int32)\n",
    "print(\"x_train.shape =\", x_train.shape)\n",
    "print(\"y_train.shape =\", y_train.shape)\n",
    "print(\"x_test.shape =\", x_test.shape)\n",
    "print(\"y_test.shape =\", y_test.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5c1b9855-3703-47fe-bd23-fe4fbd03a037",
   "metadata": {},
   "outputs": [],
   "source": [
    "model = tf.keras.models.Sequential([\n",
    "    tf.keras.layers.Conv2D(32, kernel_size=(3,3), padding='SAME', activation='relu', input_shape=x_train.shape[1:]),\n",
    "    \n",
    "    tf.keras.layers.MaxPool2D(pool_size=(2,2), strides=(1,1), padding='SAME'),\n",
    "    \n",
    "    tf.keras.layers.Dropout(0.2),\n",
    "    tf.keras.layers.Conv2D(64, kernel_size=(3,3), padding='SAME', activation='relu'),\n",
    "    \n",
    "    tf.keras.layers.Dropout(0.2),\n",
    "    tf.keras.layers.Flatten(),\n",
    "    \n",
    "    tf.keras.layers.Dense(512, activation='relu'),\n",
    "    tf.keras.layers.Dropout(0.2),\n",
    "    \n",
    "    tf.keras.layers.Dense(256, activation='relu'),\n",
    "    tf.keras.layers.Dropout(0.5),\n",
    "    tf.keras.layers.Dense(10, activation='softmax')\n",
    "])\n",
    "\n",
    "model.summary()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5125e2cd-365f-43ee-b1a8-7e43ab722247",
   "metadata": {},
   "outputs": [],
   "source": [
    "model.compile(optimizer='adam',\n",
    "              loss=tf.keras.losses.SparseCategoricalCrossentropy(),\n",
    "              metrics=['sparse_categorical_accuracy'])\n",
    "\n",
    "history = model.fit(x_train, y_train, \n",
    "                    batch_size=128, \n",
    "                    epochs=10, \n",
    "                    validation_split=0.2)\n",
    "\n",
    "model.evaluate(x_test, y_test, batch_size=64, verbose=2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d3e4c6d1-2977-4f39-ab9a-6d88ff876643",
   "metadata": {},
   "outputs": [],
   "source": [
    "acc = history.history['sparse_categorical_accuracy']\n",
    "loss = history.history['loss']\n",
    "val_acc = history.history['val_sparse_categorical_accuracy']\n",
    "val_loss = history.history['val_loss'] \n",
    "\n",
    "plt.figure(figsize=(10, 3))\n",
    "plt.subplot(1, 2, 1)\n",
    "plt.plot(loss, color='b-', label='train')\n",
    "plt.plot(val_loss, color='r-', label='validate')\n",
    "plt.ylabel('loss')\n",
    "plt.legend()\n",
    "\n",
    "plt.subplot(1, 2, 2)\n",
    "plt.plot(acc, color='b-', label='train')  \n",
    "plt.plot(val_acc, color='r-', label='validate')  \n",
    "plt.ylabel('Accuracy')\n",
    "plt.legend()\n",
    "\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cd6ab656-b357-4faa-ab64-d768ced990aa",
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.figure(figsize=(12, 6))\n",
    "for i in range(10):\n",
    "    n = np.random.randint(1, 10000)  \n",
    "    plt.subplot(2, 5, i+1)\n",
    "    plt.axis(\"off\")\n",
    "    plt.rcParams['font.sans-serif'] = ['SimHei']\n",
    "    \n",
    "   \n",
    "    plt.imshow(x_test[n])\n",
    "    \n",
    "    demo = tf.reshape(x_test[n], (1, 32, 32, 3))\n",
    "    y_pred = np.argmax(model.predict(demo))  \n",
    "    \n",
    "    \n",
    "    title = \"标签值：\" + str((y_test.numpy())[n,0]) + \"\\n预测值:\" + str(y_pred)\n",
    "    plt.title(title)\n",
    "plt.tight_layout()\n",
    "plt.show()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python [conda env:base] *",
   "language": "python",
   "name": "conda-base-py"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
